package com.neusoft.actor.controller;

import com.neusoft.actor.service.impl.ChatServiceImpl;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody;

import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/ChatClientController")
public class ChatClientController {

    private final ChatClient chatClient;
    private final ChatServiceImpl chatService;

    @Autowired
    public ChatClientController(ChatClient.Builder builder, ChatServiceImpl chatService) {
        this.chatClient = builder.build();
        this.chatService = chatService;
    }

    @PostMapping("/chat")
    public String generateResponse(String msg) {
        // 链式调用：构建提示 -> 发送请求 -> 获取文本响应
        return null;
    }

    @GetMapping("/tj")
    public String nextDay(@RequestParam(value = "query") String query) {

        Prompt prompt = new Prompt(query);
        String str = chatClient.prompt(prompt).tools(chatService)
                .call()
                .content();

        System.out.println(str);
        return str;
    }

    @GetMapping("/tj2")
    public ResponseEntity<StreamingResponseBody> nextDay2(@RequestParam(value = "query") String query) {
        Prompt prompt = new Prompt(query);

        // 创建 StreamingResponseBody 对象
        StreamingResponseBody stream = outputStream -> {
            // 使用 chatClient 获取响应内容
            String str = chatClient.prompt(prompt).tools(chatService)
                    .call()
                    .content();

            // 将内容写入输出流
            outputStream.write(str.getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
        };

        // 返回 ResponseEntity 包装的 StreamingResponseBody
        return ResponseEntity.ok(stream);
    }

    @GetMapping("/explain")
//    指定问题和AI回答语气，默认健康专家
    public String explain(@RequestParam String problem, @RequestParam(value = "style" ,defaultValue = "健康专家") String y){
        // 用户消息
        return chatClient.prompt()
                .system(s -> s.text("以{style}风格回答").param("style", y))  // 系统消息含占位符
                .user(problem)  // 用户消息
                .call()
                .content();

    }
}
